﻿/***************************  Ccay IGrid colSort  ***********************************/
(function(IGrid){
	 
	/** 给grid manager 扩展收缩展开的接口 */
	Ccay.UI.XControl.extendIManager("XGrid", {
		colsort : function(){
			var op = this.op, columns = op.columns, orderColumns = gridColSort.getOrderColumns(op);
			for(var i = 0, col; col = orderColumns[i]; i++){
				
				if(col.inner || col.columnType || !col.field){
					col._colsort = -1;
					continue;
				}
				col._colsort = i + 1;
				if(isNaN(col.colsort)){
					col.colsort = col._colsort
				}
			}
			
			var start = -1000;
			$.each( op.columns,function(){
				if(this.inner || this.columnType || !this.field){
					this.colsort = start ++;
				}
			})
			Ccay.DataHelper.sort("colsort", "asc", op.columns);
			
			$.each( op.columns,function(){
				if(this.colsort % 1 == 0){
					delete this.colsort;
				}
			})
		}
	});
	var gridColSort = IGrid.colSort = {
		
		
		init : function( grid, op ){
			
			gridColSort.setIndex(grid);
			var colPanel = $.create('div','ccay-igrid-colpanel').appendTo(grid.getContent()).data("indexCache",{});

			colPanel.append($.create('div','ccay-igrid-colpanel-move'));
			
			colPanel.append('<div class="btn clear"><span class="ccay-button ccay-botton-main"><a  class="ccay-icon confirm"></a><label>{0}</label></span><span  class=ccay-button><a  class="ccay-icon cancel"></a><label>{1}</label></span></div>'.formatText($i18n("ccay.common.button.ok"),$i18n("ccay.common.button.cancel")))
			colPanel.find("span.ccay-button:first").click(function(){
				gridColSort.drop(grid, colPanel);
			}).next().click(function(){
				colPanel.hide();
				$(document).off("mousemove.drag");
			})
			grid.getHeadTable().drop({
				activePanelCss : "",
				target:'td',
				getSignTarget:function(){
					return colPanel.find("li");
				},
				clickable : true,
				offset:true, 
				panels : colPanel.find("div.ccay-igrid-colpanel-move"),
				fnFiexdPosition : function(trigger,pos,mover,op,e){
					pos = {left :e.pageX - 20, top : e.pageY - 10};
					return pos;
				},
				onDragStart : function(e,pos,mover,trigger){
					
					if(!trigger.is("td[field]")){
						return false;
					}else{
						var allowDrag = gridColSort.start.call(this,e, grid, colPanel);
						if(allowDrag === false){
							return false;
						}
						trigger[0] = colPanel.find("li[field='"+ trigger.attr("field") +"']").addClass("self")[0];
					}
					mover.addClass("ccay-igrid-movecol").css({width:0,height:0}).html(trigger.html());
				},
				onDroped : gridColSort.onDroped
			});
		},
		
		setIndex : function(grid){
			var op = grid.op, columns = op.columns, orderColumns = gridColSort.getOrderColumns(op);
			for(var i = 0, col; col = orderColumns[i]; i++){
				col._colsort = i + 1;
			}
		},
		
		start : function(e, grid, colPanel){
			//缓存当前拖拽的列 field 
			var content = grid.getContent(), field = $(this).attr("field");
			var col = grid.op._columnMap[field],moveLine = content.children(".ccay-igrid-moveLine");
			//如果是改变宽度或这是inner column 则推出拖拽
			
			if((moveLine.length > 0 && moveLine.css("display") != "none") || col.inner || col.columnType){
				return false;
			}
			colPanel.show();
			gridColSort.initDrop(colPanel, grid);
			gridColSort.createColPanel(grid, colPanel, field);
			grid._colSortPanelText = colPanel.text();
		},
		
		drop : function(grid,  colPanel){
			
			colPanel.hide();
			$(document).off("mousemove.drag");
			//比较是否排序有过修改
			if(grid._colSortPanelText != colPanel.text()){
				gridColSort.colSort(grid, colPanel);
			}
		},
		
		
		initDrop : function(colPanel, grid){
			if(colPanel.attr("init"))
				return;
			colPanel.drop({
				activePanelCss : "",
				target:'li',
				panels : colPanel.find("div.ccay-igrid-colpanel-move"),
				fnFiexdPosition : function(trigger,pos,mover,op){
					var content = grid.getContent();
					mover.text(trigger.text()).addClass("ccay-igrid-movecol");
					var left = content.offset().left, top = content.offset().top;
					pos = {left : pos.left + left, top : pos.top + top};
					return pos;
				},
				onDragStart : function(e,pos,mover,trigger){
					if(!trigger.is("li[field]")){
						return false;
					}else{
						colPanel.find("li.self").removeClass("self");
						trigger.addClass("self");
					}
				},
				onDroped : gridColSort.onDroped

			});
			colPanel.attr("init",true);
		},
		
		onDroped :function(e,pos,mover,trigger,op){
			var colPanel =  trigger.parents(".ccay-igrid-colpanel"),item = op.actives && op.actives.item;
			var self = colPanel.find("li.self");
			if(op.actives && op.actives.item && !self.hasClass("hidden") && !self.parent().hasClass("ccay-igrid-colpanel-freezen")){
				var num = op.actives.item.parent(".ccay-igrid-colpanel-freezen").length  ? 3 : 2;
				if(colPanel.find("ul.ccay-igrid-colpanel-free").children().not(".hidden").length < num){
					Ccay.UI.topBox("ccay.common.message.notFreezeAll");
					return false;
				}
			}
			if(op.actives && !op.actives.item){
				op.actives.panel[0] = colPanel.find("ul.ccay-igrid-colpanel-free")[0];
			}
			if((item && item[0] != trigger[0] && gridColSort.getPrevCol(item)[0] != trigger[0]) || (!item && colPanel.find("li:last")[0] !== trigger[0]) ){
				trigger.attr("move",true)
			}
			return true;
		},
		
		createColPanel : function( grid, colPanel, moveField){
			
			var htmls = ["<ul class='ccay-igrid-colpanel-freezen'><A class='ccay-icon lock' title=lock></A>"],cols = this.getOrderColumns(grid.op),freezeSplit = false;
			for( var i = 0, col; col = cols[i]; i++){
				var field = col.field;
				if(!col.freezeable && !freezeSplit){
					htmls.push("<li class='ccay-igrid-colpanel-line'>line</li></ul><ul class='ccay-igrid-colpanel-free'>");
					freezeSplit = true;
				}
				var cls = (field == moveField ? " self" : "") + (col.freezeable ? " freeze" : "") +  (col.hidden ? " hidden" : "") ;
				htmls.push("<li field='{0}' class='{1}' index={2}>{3}</li>".formatText(field, cls , col._colsort ++, col.header ? $i18n(col.header) :col.customHeader));
			}
			if(!freezeSplit){
				htmls.push("<li class='ccay-igrid-colpanel-line'>line</li></div>");
			}
			htmls.push("</ul>")
			colPanel.find("div.ccay-igrid-colpanel-move").html(htmls.join(""));
		},
		
		getOrderColumns:function(op){
			var fzCols = [],cols = [];
			$.each(op.columns,function(i,col){
				if(col.inner || col.columnType || !col.field){
					return;
				}
				(op.allowFreezen && col.freezeable ? fzCols : cols).push(col);
			});
			return fzCols.concat(cols);
		},

		colSort: function(grid, colPanel) {
            var op = grid.op;

            /** 变量说明 columns : 原有展现顺序的列设置对象数组， newColumns 用来保存新顺序的列设置对象数组
             *  oldIndex 拖拽的列在columns中的原有索引， newIndex 用来保存计算出来的 新索引
             *  moveCol 拖拽列的设置对象
             */
            var columns = op.columns, newColumns = [],  hideColumns = [], _newCol = [], _hideCol = [];

            $.each(op.columns, function(i, col) {
                if ((col.inner || col.columnType || !col.field) && !col.lockEnd) {
                    newColumns.push(col);
                }
            });
            var preCol = null;
            colPanel.find("li[field]").each(function(i) {
                var li = $(this),  field = li.attr("field"),  col = op._columnMap[field];
                var hasMove = li.is("[move]"), isChange = false;

                if (hasMove) {
                    col.colsort = preCol ? ((preCol.colsort || preCol._colsort) + 0.01) : 0.01;
                    isChange = true;
                } else {
                    if (preCol && col.colsort && col.colsort == preCol.colsort) {
                        col.colsort += 0.01;
                        isChange = true;
                    }
                }

                if ($(this).nextAll("li.ccay-igrid-colpanel-line").length > 0) {
                    if (!col.freezeable) {
                        col.freezeable = true;
                        isChange = true;
                    }
                } else {
                    if (col.freezeable) {
                        isChange = true;
                        col.freezeable = false;
                    }
                }
                if(isNaN(col.colsort)){
						col.colsort = col._colsort;
						isChange = true;
				} 
                newColumns.push(col);
                isChange && _newCol.push({
                    field: col.field,
                    hidden: col.hidden,
                    freezeable: col.freezeable,
                    colsort: col.colsort
                });

                preCol = col;
            });
            
            //主要针对操作处理，操作是否锁定到最后。
            $.each(op.columns, function(i, col) {
                if ((col.inner || col.columnType || !col.field) && col.lockEnd) {
                    newColumns.push(col);
                }
            });
            
            // 保存列顺序
            op.columns = newColumns;
            grid.op.customSetting && grid.saveCustom({
                hasColSort: true,
                showMessage:false,
                columns: _newCol
            });
            colPanel.empty();
            op._scrollTop = grid.getBodyPanel().scrollTop();
            // 重新初始化
            grid.reInit({
                _hasColSort: true,
                columns: newColumns
            });
        },

		getPrevCol : function(currCol){
			var col = currCol.prev("li");
			if(col.length == 0){
				col =  currCol.parent().prev(".ccay-igrid-colpanel-freezen").children("li[field]:last");
			}
			return col;
		}
			
	
	};
	
	

	//注册表头插件
	Ccay.UI.XControl.addPlugin("XGrid", "colsort", {
	    build: function (grid, op) {
	    	if(!op.customHead && op.colsort !== false ){
	    		op.handler.initComplete.add(gridColSort.init);
	    	}
	    },
	    clear: function (grid, op, oldOp) {
	    	if (oldOp._scrollTop) {
	    		op._scrollTop = oldOp._scrollTop;
	    	}
	    	if(op.Storage && op.Storage.dataset.length > 0){
	    		op.autoLoad = true;
	    	}
	    }
	});
})(Ccay.UI.IGrid);